<?php

namespace common\models\base;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%base_options}}".
 *
 * @property int $id
 * @property string $scope 应用范围名称
 * @property string $name 名称
 * @property string $value 值
 * @property int $listorder 排序
 * @property int $disabled 开启状态：0开启，1关闭
 */
class BaseOptions extends \common\db\ActiveRecord {

    use \common\traits\Constants;

    const CACHE_NAME = 'BaseOptions';

    /**
     * 禁用状态
     * @var DISABLED_ON  1  禁用
     * @var DISABLED_OFF  0  启用
     */
    const DISABLED_ON = 1;
    const DISABLED_OFF = 0;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%base_options}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['scope', 'name'], 'required'],
            [['disabled', 'listorder'], 'integer'],
            [['scope', 'name'], 'string', 'max' => 64],
            [['value'], 'string', 'max' => 255],
            [['scope', 'name'], 'unique', 'targetAttribute' => ['scope', 'name']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'scope' => '应用范围名称',
            'name' => '名称',
            'value' => '值',
            'disabled' => '开启状态：0开启，1关闭',
            'listorder' => '排序',
        ];
    }

    public function getTopProducts($count = 10) {
        $cache = Yii::$app->cache; // Could be Yii::$app->cache
        return $cache->getOrSet(['top-n-products', 'n' => $count], function ($cache) use ($count) {
            return Products::find()->mostPopular()->limit(10)->all();
        });
    }

    public static function getOptionList() {
        return Yii::$app->cache->getOrSet(self::CACHE_NAME, [static::className(), 'setOptionList']);
    }

    public static function setOptionList() {
        $data = static::find()
        ->select(['scope', 'name', 'value'])
        ->where(['disabled' => self::DISABLED_OFF])
        ->orderBy(['scope' => SORT_ASC, 'listorder' => SORT_ASC])
        ->asArray()
        ->all();
        return ArrayHelper::map($data, 'value', 'name', 'scope');
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        static::setOptionList();
    }

    public function afterDelete() {
        parent::afterDelete();
        static::setOptionList();
    }

}
